package com.hzzc.sso.sdk.session;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SsoSession implements HttpSession {

    private String id;

    private Map<String, Object> datas = new ConcurrentHashMap();

    private long createTime = System.currentTimeMillis();

    private long lastAccessTime = System.currentTimeMillis();

    public SsoSession(String id) {
        this.id = id;
    }

    @Override
    public long getCreationTime() {
        return createTime;
    }

    /**
     * 更新最新的访问时间
     *
     * @return
     */
    public long updateLastAccessTime() {
        return this.lastAccessTime = System.currentTimeMillis();
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public long getLastAccessedTime() {
        return lastAccessTime;
    }

    @Override
    public ServletContext getServletContext() {
        throw new RuntimeException("当前操作不支持");
    }

    @Override
    public void setMaxInactiveInterval(int i) {
        throw new RuntimeException("当前操作不支持");
    }

    @Override
    public int getMaxInactiveInterval() {
        throw new RuntimeException("当前操作不支持");
    }

    @Override
    public HttpSessionContext getSessionContext() {
        throw new RuntimeException("当前操作不支持");
    }

    @Override
    public Object getAttribute(String s) {
        return datas.get(s);
    }

    @Override
    public Object getValue(String s) {
        return datas.get(s);
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        throw new RuntimeException("当前操作不支持");
    }

    @Override
    public String[] getValueNames() {
        return datas.keySet().toArray(new String[0]);
    }

    @Override
    public void setAttribute(String s, Object o) {
        datas.put(s, o);
    }

    @Override
    public void putValue(String s, Object o) {
        datas.put(s, o);
    }

    @Override
    public void removeAttribute(String s) {
        datas.remove(s);
    }

    @Override
    public void removeValue(String s) {
        datas.remove(s);
    }

    /**
     * 是否过期
     *
     * @param duration
     */
    public boolean isExpired(long duration) {
        if (System.currentTimeMillis() - getLastAccessedTime() > duration) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void invalidate() {
        throw new RuntimeException("当前操作不支持");
    }

    @Override
    public boolean isNew() {
        throw new RuntimeException("当前操作不支持");
    }
}
